<?php
/**
 * Handles all calendar and event functions
 *
 *
 *  @author Jimmy E. Lewis
 *  @version 1.0
 */

class Calendar extends Controller{
	
	function __construct() {
		parent::__construct();
		$this->load->model('UserModel');
		$this->load->model('CalendarModel');
		$this->load->helper('date');
	}
	function index(){
		$this->full();
	}
	
	//---------------------- Function To Display Calendar ----------------------//
	
	function calendar1(){
		if($this->validMonth($this->uri->segment(3))){
			$month = $this->uri->segment(3);
		}
		else{
			$month = date('n');
		}
		
		$day = 1;

		if($this->validYear($this->uri->segment(4))){
			$year = $this->uri->segment(4);
		}
		else{
			$year = date('Y');
		}
			$period = date("t",mktime(0,0,0,$month,1,$year));

		$start = mktime(0,0,0,$month,$day,$year);

		$dates = $this->_createCalendar($month,$day,$year);
		$a = 0;
		$b= $start;
		//get events for month
		while($a<$period){
			$start = mktime(0,0,0,$month,$day+$a,$year);
			$end = mktime(23,59,59,$month,$day+$a,$year);	

			$events = $this->CalendarModel->getEvents($start,$end);
			if($events->num_rows() > 0){
				foreach($events->result() as $row){
					$days[date("j",$start)][] = array(
													'start' => $row->start,
													'end' => $row->end,
													'name' => $row->name,
													'description' => $row->description,
													'location' => $row->location,
													'id' => $row->id
												);
				}


			}
			$a++;

		}
		if(isset($days)) $data = array( 'events' => $days, 'dates' => $dates, 'date' => $b); //if the month has events 
		else $data = array('dates' => $dates, 'date' => $b);
		$data['event'] = $this->CalendarModel->getEvent($this->uri->segment(5));
		$data['items'] = $this->CalendarModel->getItems($this->uri->segment(5));
		if ($this->session->userdata('loggedin')) $data = $data + $this->_buildContent();
		else {
			$data['extraHead'] = '<link rel="stylesheet" href="'.base_url().'css/static.css" type="text/css" />';
			$data['pagetype'] = 'nobg';
		}
		($this->uri->segment(5)=='cal_only') ? $this->load->view('calendar/calendarView',$data) : $this->load->view('calendar/fullView',$data);
		$this->load->view('calendar/calendarWithEvent',$data);
	}
	
	
	/**
	 * Displays a full size calendar.
	 *
	 * @param int month -- sets the display month. Defaults to current month if not set.
	 * @param int year -- sets the display year.  Defaults to current year if not set.
	 * @param String 'cal_only' -- Only displays the html that makes up the calendar.  
	 *		 In order to use this you must enter a month and year also.
	 */
	function full(){
			if($this->validMonth($this->uri->segment(3))){
				$month = $this->uri->segment(3);
			}
			else{
				$month = date('n');
			}
			
			$day = 1;

			if($this->validYear($this->uri->segment(4))){
				$year = $this->uri->segment(4);
			}
			else{
				$year = date('Y');
			}
				$period = date("t",mktime(0,0,0,$month,1,$year));

			$start = mktime(0,0,0,$month,$day,$year);

			$dates = $this->_createCalendar($month,$day,$year);
			$a = 0;
			$b= $start;
			//get events for month
			while($a<$period){
				$start = mktime(0,0,0,$month,$day+$a,$year);
				$end = mktime(23,59,59,$month,$day+$a,$year);	

				$events = $this->CalendarModel->getEvents($start,$end);
				if($events->num_rows() > 0){
					foreach($events->result() as $row){
						$days[date("j",$start)][] = array(
														'start' => $row->start,
														'end' => $row->end,
														'name' => $row->name,
														'description' => $row->description,
														'location' => $row->location,
														'id' => $row->id
													);
					}


				}
				$a++;

			}
			if(isset($days)) $data = array( 'events' => $days, 'dates' => $dates, 'date' => $b); //if the month has events 
			else $data = array('dates' => $dates, 'date' => $b);
			if ($this->session->userdata('loggedin')) $data = $data + $this->_buildContent();
			else {
				$data['extraHead'] = '<link rel="stylesheet" href="'.base_url().'css/static.css" type="text/css" />';
				$data['pagetype'] = 'nobg';
			}
			($this->uri->segment(5)=='cal_only') ? $this->load->view('calendar/calendarView',$data) : $this->load->view('calendar/fullView',$data);
	}
	
	/**
	 * Displays a full size calendar.
	 *
	 * @param int month -- sets the start month. Defaults to current month if not set.
	 * @param int day -- sets the start day.  Defaults to current day if not set.
	 * @param int year -- sets the start year.  Defaults to current year if not set.
	 * @param int period -- sets the number of days to get events for.  Defaults to 14.
	 *		 In order to use this you must enter a month, day, and year also.
	 */
	function agenda(){
		if($this->validMonth($this->uri->segment(3))){
			$month = $this->uri->segment(3);
		}
		else{
			$month = date('n');
		}
		if($this->validDay($this->uri->segment(4))){
			$day = $this->uri->segment(4);
		}
		else{
			$day = date('j');
		}
		if($this->validYear($this->uri->segment(5))){
			$year = $this->uri->segment(5);
		}
		else{
			$year = date('Y');
		}
		if($this->validPeriod($this->uri->segment(6))){
			$period = $this->uri->segment(6);
		}
		else{
			$period = 14;
		}
		$a = 0;
		while($a<=$period){
			
			$start = mktime(0,0,0,$month,$day+$a,$year);
			$end = mktime(23,59,59,$month,$day+$a,$year);	
			
			$events = $this->CalendarModel->getEvents($start,$end);
			if($events->num_rows() > 0){
				foreach($events->result() as $row){
					$days[date("Y-n-j",$start)][] = array(
													'date' => $start,
													'start' => $row->start,
													'end' => $row->end,
													'name' => $row->name,
													'description' => $row->description,
													'location' => $row->location,
													'id' => $row
												);
				}
				
			
			}
			$a = $a + 1;
			
		}
		

		if(isset($days)) $data = array( 'events' => $days);
//		$data = $data + $this->_buildContent();
		(isset($days)) ? $this->load->view('calendar/listView',$data) : $this->load->view('calendar/listView');
	}
	
	/**
	 * Displays the next seven days.
	 */
	function week(){
		$month = date('n');
		$day = date('j');
		$year = date('Y');
				
		$period = 7;

		$a = 0;
		while($a<$period){
			$start = mktime(0,0,0,$month,$day+$a,$year);
			$end = mktime(23,59,59,$month,$day+$a,$year);	
			
			$events = $this->CalendarModel->getEvents($start,$end);
			
			if($events->num_rows() > 0){
//				echo "<br>" . $events->num_rows();
				foreach($events->result() as $row){
					$days[date("Y-n-j",$start)][] = array(
													'date' => $start,
													'start' => $row->start,
													'end' => $row->end,
													'name' => $row->name,
													'description' => $row->description,
													'location' => $row->location,
													'id' => $row
												);
				}
				
			
			}
			$a++;
			
		}
		
		$dates = $this->_createWeekly($month,$day,$year,"7");
		
		if(isset($days)) $data = array( 'events' => $days, 'week' => $dates['dates'], 'dayOrder' => $dates['dayOrder']);
		else $data = array('week' => $dates['dates'], 'dayOrder' => $dates['dayOrder']);

		$this->load->view('calendar/weekView',$data);
	}
	
	//---------------------- Functions Make Calendar ----------------------//
	
	/**
	 * Creates the arrays for a weekly calendar.  Sets both the day names and numbers.
	 */
	function _createWeekly($month,$day,$year,$period){
		$start = mktime(0,0,0,$month,$day,$year);
		$a = 0;
		while($a<$period){
			$dayOrder[] = date("l",strtotime("+$a days",$start));
			$dates[] = date("Y-n-j",strtotime("+$a days",$start));
			$a++;
		}
		$data = array('dates' => $dates, 'dayOrder' => $dayOrder);
		return $data;
	}

	/**
	 * Creates the arrays for a full calendar.
	 */
	function _createCalendar($month,$day,$year){
		$date = mktime(0,0,0,$month,1,$year);
		$daysInMonth = date("t",mktime(0,0,0,$month,1,$year));
		$firstDay = date("w",mktime(0,0,0,$month,1,$year));

		$tempDays = $firstDay + $daysInMonth;
		$weeksInMonth = ceil($tempDays/7);


		$counter = 0;

		for($j=0;$j<$weeksInMonth;$j++) {
			for($i=0;$i<7;$i++) {
				$counter++;
				$week[$j][$i] = $counter;
				// offset the days
				$week[$j][$i] -= $firstDay;
				if (($week[$j][$i] < 1) || ($week[$j][$i] > $daysInMonth)) {    
					$week[$j][$i] = "";
				}
			}
		}
		return $week;
		
	}
	
	//---------------------- Functions For Items ----------------------//
	
	function assignItem(){
		$id = $this->uri->segment(3);
		$item = $this->CalendarModel->getItem($id);
		//Has this item aready been assigned?
		if($item->assign==""){
			$post['assign'] = $this->uri->segment(4);
			$this->CalendarModel->assignItem($id,$post);
		}
		$event = $this->CalendarModel->getEventForItem($id);
		$event->month = date("n",strtotime($event->start));
		$event->year = date("n",strtotime($event->start));
		redirect("calendar/calendar1/$event->month/$event->year/$event->id");
	}
	
	/**
	 * Displays page: This is the write page for composing an item
	 */
	function createItem(){
		$this->badger->checkAllow('admin staff xalt');
		if($this->UserModel->isUserInGroup($this->session->userdata('username'),$this->UserModel->getGroupID('xalt'))) $data = $this->_buildContent();
		else $data = $this->_buildAdminContent();
		$this->load->library('validation');
		
		$rules['name'] = "trim|required";
		
		$this->validation->set_rules($rules);
		
		$fields['name']	= 'name';
		$fields['event_id']	= 'event_id';
		
		$this->validation->set_fields($fields);
	
		$this->validation->set_error_delimiters('<div class="error">','</div>');
		
		if($this->validation->run() == FALSE) {
			$this->load->view('calendar/createItem',$data);
		} else {
			$post['name'] = $this->input->post('name',TRUE);
			$post['event_id'] = $this->input->post('event_id',TRUE);

			$this->CalendarModel->createItem($post);
			if($data['admin']) redirect('admin/events');
			else redirect('calendar/full');
		}
	}
	
	/**
	 * Displays page to allow editing an item.  The editor must be an admin, xalt, of staff member
	 */
	function editItem(){
		$this->badger->checkAllow('admin staff xalt');
		$this->load->model('CalendarModel');
		$data['event'] = $this->CalendarModel->getEvent($this->uri->segment(3));
		$data = $data + $this->_buildContent();
		$this->load->view('calendar/item_edit', $data);
	
	}
	
	/**
	 * Displays page to allow deleting an item.  The deleter must be an admin, xalt, of staff member
	 */
	function deleteItem(){
		$this->badger->checkAllow('admin staff xalt');
		$this->load->model('CalendarModel');
		$this->CalendarModel->deleteItem($this->uri->segment(3));
		$data['admin'] = $this->UserModel->isUserInGroup($this->UserModel->getUserID($this->session->userdata('username')),$this->UserModel->getGroupID('admin'));
		if($data['admin']) redirect('admin/events');
		else redirect('calendar/full');
		
	}
	
	/**
	 * Displays the items for an event
	 */
	function event_items(){
		$this->badger->checkAllow('admin');
		$items = $this->CalendarModel->getItems($this->uri->segment(3));
		foreach($items->result() as $row) {
			if($row->assign!=""){
				$row->author = $this->UserModel->getUsername($row->assign);
				$row->authorname = $this->UserModel->getDisplayName($row->assign);
			}
		}
		$data['items'] = $items;
		$data['event'] = $this->uri->segment(3);
		$data = $data + $this->_buildAdminContent();
		$this->load->view('calendar/eventItems', $data);
	}
	
	//---------------------- Functions For Events ----------------------//
	
	
	/**
	 * Displays page: This is the write page for composing a event
	 */
	function create(){
		$this->badger->checkAllow('admin staff xalt');
		$data = $this->_buildContent();
		$this->load->library('validation');
		
		$rules['name'] = "trim|required";
		$rules['description'] = "trim|required|required";
		$rules['start'] = "trim|required";
		$rules['end'] = "trim|required";
		$rules['location'] = "trim|required";
		
		$this->validation->set_rules($rules);
		
		$fields['name']	= 'name';
		$fields['description']	= 'description';
		$fields['start']	= 'start';
		$fields['start_time'] = 'start_time';
		$fields['end']	= 'end';
		$fields['end_time'] = 'end_time';
		$fields['location']	= 'location';
		$this->validation->set_fields($fields);
	
		$this->validation->set_error_delimiters('<div class="error">','</div>');
		
		if($this->validation->run() == FALSE) {
			$this->load->view('calendar/createEvent',$data);
		} else {
			$post['name'] = $this->input->post('name',TRUE);
			$post['description'] = $this->input->post('description',TRUE);
			$post['start'] = $this->input->post('start',TRUE) . ' ' . $this->input->post('start_time',TRUE);
			$post['end'] = $this->input->post('end',TRUE) . ' ' . $this->input->post('end_time',TRUE);
			$post['location'] = $this->input->post('location',TRUE);
			$this->CalendarModel->createEvent($post);
			if($data['admin']) redirect('admin/events');
			else redirect('calendar/full');
		}
	}
	
	/**
	 * Displays page to allow deleting an event.  The deleter must be an admin, xalt, of staff member
	 */
	function deleteEvent(){
		$this->badger->checkAllow('admin staff xalt');
		$this->load->model('CalendarModel');
		$this->CalendarModel->deleteEvent($this->uri->segment(3));
		$data['admin'] = $this->UserModel->isUserInGroup($this->UserModel->getUserID($this->session->userdata('username')),$this->UserModel->getGroupID('admin'));
		if($data['admin']) redirect('admin/events');
		else redirect('calendar/full');
	}
	
	/**
	 * Displays page to allow editing an event.  The editor must be an admin, xalt, of staff member
	 */
	function editEvent(){
		$this->badger->checkAllow('admin staff xalt');
		$this->load->model('CalendarModel');
		$data['event'] = $this->CalendarModel->getEvent($this->uri->segment(3));
		$data['admin'] = $this->UserModel->isUserInGroup($this->UserModel->getUserID($this->session->userdata('username')),$this->UserModel->getGroupID('admin'));
		$data = $data + $this->_buildContent();
		$this->load->view('calendar/event_edit', $data);
	
	}
	
	/**
	 * Edits a post with submitted information
	 */
	function doEditPost() {
		//needs valadation 
		$this->badger->checkAllow('admin staff xalt');
		$this->load->model('CalendarModel');
		$post['name'] = $this->input->post('name', TRUE);
		$post['description'] = $this->input->post('description', TRUE);
		$post['start'] = $this->input->post('start',TRUE) . ' ' . $this->input->post('start_time',TRUE);
		$post['end'] = $this->input->post('end', TRUE) . ' ' . $this->input->post('end_time',TRUE);
		$post['location'] = $this->input->post('location');
//		$post['category'] = $this->input->post('category');
		$post['category'] = 'XA';
		$id = $this->input->post('id');
			
		$this->load->model('CalendarModel');
		$this->CalendarModel->updateEvent($id,$post);
		
		if($this->UserModel->isUserInGroup($this->UserModel->getUserID($this->session->userdata('username')),$this->UserModel->getGroupID('admin'))) redirect('admin/events');
		else redirect('calendar/full');
	}
	
	/*
	 * Displays and event and it's items.
	 */
	function event($id){
		$event = $this->CalendarModel->getEvent($id);
		$items = $this->CalendarModel->getItems($id);
		$data = array(
						'event' => $event, 
						'items' => $items
				);
		$data = $data + $this->_buildContent();
		$this->load->view('calendar/eventView',$data);
	}
	
	
	
	function validMonth($month){
		if($month!='' && is_numeric($month) && $month>=1 && $month<=12){
			return true;
		}

		return false;
	}
	
	function validDay($day){
		if($day!='' && is_numeric($day) && $day>=1 && $day<=31){
			return true;
		}

		return false;
	}
	
	function validYear($year){
		if($year!='' && is_numeric($year) && strlen($year)==4 && $year>=1970 && $year<=2032){
			return true;
		}

		return false;
	}
	
	function validPeriod($period){
		if($period!='' && is_numeric($period) && $period>=1){
			return true;
		}

		return false;
	}
	/*
	 * Supplies user-specific information to the interface for customization
	 */
	function _buildContent() {
		//REQUIRED//
		$data['sidebar'] = TRUE;
		if ($this->session->flashdata('msg_info')) $data['msg_info'] = $this->session->flashdata('msg_info');
		if ($this->session->flashdata('msg_error')) $data['msg_error'] = $this->session->flashdata('msg_error');
		
		//test if user is logged in for site navigation
		if ($this->session->userdata('loggedin')) {
			$data['loggedin'] = TRUE;
			//grab the user
			$user = $this->UserModel->getUserByName($this->session->userdata('username'));
			$user->display = $this->UserModel->getDisplayName($user->userid);
		

			//is admin?
			if ($this->UserModel->isUserInGroup($user->userid,$this->UserModel->getGroupID('admin'))) {
				$data['links'] = '<a  href="'.site_url("admin").'">admin</a> | <a href="'.site_url("site/logout").'">logout</a>';
				$data['admin'] = true;
			} else {
				$data['links'] = '<a href="'.site_url("site/logout").'">logout</a>';
				$data['admin'] = false;
			}
			
			//is xalt?
			if ($this->UserModel->isUserInGroup($user->userid,$this->UserModel->getGroupID('xalt'))) {
				$data['page_info']['title'] = 'calendar';
				$data['page_info']['items'] = array(anchor('calendar/create', 'Compose an event entry'));
				$data['xalt'] = true;
			}
			else $data['xalt'] = false;
			
			$data['con_user'] = $user;
		}
		
		
		
		return $data;
	}
	
	/*
	 * Admin: Supplies user-specific information to the interface for customization
	 */
	function _buildAdminContent() {
		//REQUIRED//
		$data['pagetype'] = 'page-admin';
		$data['admin_nav'] = TRUE;
		$data['admin'] = true;
		
		return $data;
	}
	
}
?>
